<template>
  <!-- ACD管理 -->
  <el-dialog
    :title="$t('m.ACD_MANAGEMENT')"
    custom-class="acd-dialog"
    :close-on-click-modal="false"
    :modal="false"
    :visible.sync="acdDialog"
    :before-close="handleClose"
  >
    <el-table
      :data="tableData"
      ref="acdTable"
      height="400"
      style="width: 100%"
      :highlight-current-row="true"
      cell-class-name="table-cell-custom"
      header-cell-class-name="table-herder-custom"
      size="small"
    >
      <el-table-column width="55" type="selection" align="center"></el-table-column>
      <el-table-column prop="acdGroupName" show-overflow-tooltip :label="$t('m.ACD_GROUP')"></el-table-column>
      <el-table-column prop="acdCallin" :label="$t('m.ACCESS_NUMBER')"></el-table-column>
      <el-table-column prop="acdUrgentCallin" :label="$t('m.EMERGENCY_ACCESS_NUMBER')"></el-table-column>
      <el-table-column prop="callStrategy" :label="$t('m.ASSIGNMENT_STRATEGY')">
        <template slot-scope="scope">
          <span>{{$t('m.dict.callStrategy')[scope.row.callStrategy]}}</span>
        </template>
      </el-table-column>
      <el-table-column align="center">
        <template slot-scope="scope">
          <el-link icon="el-icon-edit" @click="handleEdit(scope.row)">{{$t('m.EDIT')}}</el-link>
        </template>
      </el-table-column>
    </el-table>
    <div slot="footer" class="dialog-footer">
      <el-button @click="handleAcdDialogAdd()" size="small">{{$t('m.ADD')}}</el-button>
      <el-button @click="handledel()" size="small">{{$t('m.DELECT')}}</el-button>
    </div>
    <!-- 新增界面 -->
    <el-dialog
      :title="$t('m.ACD_MANAGEMENT')"
      custom-class="inner-dialog"
      :close-on-click-modal="false"
      :modal="false"
      :visible.sync="acdDialogAdd"
      :before-close="handleAddClose"
      width="100%"
    >
      <svg-icon class="back-to-list" icon-class="back" @click="dialogClose()"></svg-icon>
      <div style="height:360px">
        <el-scrollbar wrap-style="overflow-x:hidden;height:350px" style="height:100%;">
          <el-form
            ref="form"
            :model="form"
            label-width="120px"
            hide-required-asterisk
            :rules="rules"
          >
            <el-form-item :label="$t('m.ACD_GROUP')" prop="acdGroupName">
              <el-input size="small" v-model="form.acdGroupName" :disabled="disabled"></el-input>
            </el-form-item>
            <el-form-item :label="$t('m.ACCESS_NUMBER')" prop="acdCallin">
              <el-input size="small" v-model="form.acdCallin" :disabled="disabled"></el-input>
            </el-form-item>
            <el-form-item :label="$t('m.EMERGENCY_ACCESS_NUMBER')" prop="acdUrgentCallin">
              <el-input size="small" v-model="form.acdUrgentCallin" :disabled="disabled"></el-input>
            </el-form-item>
            <el-form-item :label="$t('m.EMERGENCY_CALLOUT_NUMBER')" prop="urgentNum">
              <el-input size="small" v-model="form.urgentNum" :disabled="disabled"></el-input>
            </el-form-item>
            <el-form-item :label="$t('m.TIMEOUT_M')" prop="outTime">
              <el-input size="small" v-model="form.outTime" :disabled="disabled"></el-input>
            </el-form-item>
            <el-form-item :label="$t('m.ASSIGNMENT_STRATEGY')" prop="callStrategy">
              <el-select
                v-model="form.callStrategy"
                :placeholder="$t('m.tip.PLEASE_SELECT')"
                popper-class="default-select-popper"
              >
                <el-option
                  v-for="item in callStrategyMap"
                  :key="item.key"
                  :label="$t('m.dict.callStrategy')[item.key]"
                  :value="item.key"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item :label="$t('m.MEET_ACCESS_NUMBER')" prop="acdMeetNum ">
              <el-input size="small" v-model="form.acdMeetNum " :disabled="disabled"></el-input>
            </el-form-item>
            <el-form-item
              :label="$t('m.RELEVANCE_DISPATCH_GROUP')"
              prop="group"
              class="form-item-group"
            >
              <div class="group-item" v-for="(item, index) in form.group" :key="index">
                <div>
                  <svg-icon icon-class="remove" @click="removeList(form.group,index)"></svg-icon>
                </div>
                <el-input v-model="item.groupName" style="width:300px" disabled></el-input>
                <img
                  class="img-threeDian"
                  src="../../assets/mainMenuImg/three_dian.png"
                  @click="addGroup(index)"
                />
                <el-select
                  v-model="item.priority"
                  :placeholder="$t('m.tip.PLEASE_SELECT')"
                  style="margin-left:5px"
                  popper-class="default-select-popper"
                >
                  <el-option
                    :key="item.key"
                    :label="$t('m.PRIORITY')+item.key"
                    :value="item.key"
                    v-for="item in priorityMap"
                  ></el-option>
                </el-select>
              </div>
              <div class="group-item add">
                <svg-icon icon-class="plus" @click="addGroupDemo()"></svg-icon>
                <label class="add-label" @click="addGroupDemo()">{{$t('m.ADD_DISPATCH_GROUP')}}</label>
                <!-- <span class="valid-rule">{{groupValid}}</span> -->
              </div>
            </el-form-item>
          </el-form>
        </el-scrollbar>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button
          @click="dialogStatus == 'add'?handleCreate():handleUpdate()"
          size="small"
        >{{$t('m.CONFIRM')}}</el-button>
      </div>
    </el-dialog>
    <!-- 组选择 -->
    <div class="default-select-tree groupTree" v-show="showTree">
      <el-scrollbar class="tree-scrollbar" wrap-class="tree-scrollbar__wrap">
        <el-tree
          :data="userGroupTreeData"
          icon-class="el-icon-arrow-right"
          node-key="nid"
          highlight-current
          @check-change="groupCheckChange"
          :filter-node-method="groupFilter"
          check-strictly
          ref="groupTree"
        ></el-tree>
      </el-scrollbar>
      <el-button @click="commitGroup">{{$t('m.CONFIRM')}}</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { mapGetters } from 'vuex'
import { acdgroup, getAcd } from '@/api/dataManage'
import { dataflow } from '@/api/data'
import deepClone from '@/utils/clone'
export default {
  props: {
    acdDialog: Boolean,
  },
  components: {},
  data() {
    return {
      tableData: [],
      acdDialogAdd: false,
      form: { group: [] },
      showTree: false,
      value: '',
      groupIndex: '',
      callStrategyMap: [
        {
          key: 'ringall',
          value: '空闲同振',
        },
        {
          key: 'ringroll',
          value: '循环轮振',
        },
        {
          key: 'ringpriority',
          value: '空闲轮振',
        },
      ],
      priorityMap: [
        {
          key: 1,
          value: '优先级1',
        },
        {
          key: 2,
          value: '优先级2',
        },
        {
          key: 3,
          value: '优先级3',
        },
        {
          key: 4,
          value: '优先级4',
        },
        {
          key: 5,
          value: '优先级5',
        },
        {
          key: 6,
          value: '优先级6',
        },
        {
          key: 7,
          value: '优先级7',
        },
      ],
      disabled: false,
      dialogStatus: 'add',
      // rules: {
      //   acdGroupName: [
      //     { required: true, message: '组名不能为空', trigger: 'blur' },
      //   ],
      //   acdCallin: [
      //     { required: true, message: '接入号不能为空', trigger: 'blur' },
      //   ],
      //   acdUrgentCallin: [
      //     { required: true, message: '紧急接入号不能为空', trigger: 'blur' },
      //   ],
      //   callStrategy: [
      //     { required: true, message: '请选择呼叫策略', trigger: 'change' },
      //   ],
      // },
      delGroupList: [],
    }
  },
  filters: {
    statusFilter(status) {
      const statusMap = {
        ringall: '空闲同振',
        ringroll: '循环轮振',
        ringpriority: '空闲轮振',
      }
      return statusMap[status]
    },
  },
  computed: {
    ...mapGetters(['userGroupTreeData', 'groupMap']),
    rules() {
      return {
        acdGroupName: [
          {
            required: true,
            message: this.$t('m.ACD_GROUP') + this.$t('m.tip.CAN_NOT_BE_EMPTY'),
            trigger: 'blur',
          },
        ],
        acdCallin: [
          {
            required: true,
            message: this.$t('m.tip.CAN_NOT_BE_EMPTY'),
            trigger: 'blur',
          },
        ],
        acdUrgentCallin: [
          {
            required: true,
            message: this.$t('m.tip.CAN_NOT_BE_EMPTY'),
            trigger: 'blur',
          },
        ],
        callStrategy: [
          {
            required: true,
            message: this.$t('m.tip.CAN_NOT_BE_EMPTY'),
            trigger: 'change',
          },
        ],
      }
    },
  },
  methods: {
    init() {
      this.getList()
    },
    eventMore(e) {
      let _this = this
      console.log(e)
      switch (e.type) {
        case 'AcdGroupAdd':
          if (e.result == 'succ') {
            this.handleAddACD(e.acdGroupID)
          }
          break
        case 'AcdGroupMod':
          if (e.result == 'succ') {
            this.handleAddACD(e.acdGroupID)
          }
          break
        case 'AcdAdd':
          if (e.result == 'fail') {
            if (e.reason == '173:disgroup already exist relation acd group') {
              this.$message.error(
                '配置关联调度组失败：该调度组已被其他ACD组配置'
              )
              return
            }
            this.$message.warning('配置关联调度组失败')
          }
          break
        default:
          break
      }
    },
    //获取列表
    getList() {
      acdgroup().then((res) => {
        if (res.status != 200) {
          this.$message.warning('查询失败')
        } else {
          this.tableData = res.data.eventdata
        }
      })
    },
    //打开新增
    handleAcdDialogAdd() {
      this.acdDialogAdd = true
      this.disabled = false
      this.dialogStatus = 'add'
      this.form = { group: [] }
    },
    //打开编辑
    handleEdit(item) {
      let _this = this
      this.dialogStatus = 'update'
      this.form = deepClone(item)
      this.acdDialogAdd = true
      if (this.form.group == undefined) {
        this.form.group = []
      }
      this.handleGetAcd(this.form.acdGroupID)
      this.$forceUpdate()
      // this.$nextTick(() => {
      //   _this.$refs['form'].resetFields()
      // })
    },
    //关闭
    handleClose() {
      this.$emit('update:acdDialog', false)
    },
    // 添加组按钮
    addGroupDemo() {
      let obj = { groupID: '', groupName: '', priority: 1 }
      if (this.form.group == undefined) {
        this.form.group = []
      }
      this.form.group.push(obj)
      this.$forceUpdate()
    },
    addGroup(index) {
      this.showTree = true
      this.groupIndex = index
      this.$nextTick(() => {
        this.$refs.groupTree.filter()
        this.form.group.forEach((item) => {
          let node = this.groupMap.get(item.groupID)
          if (node) {
            this.$refs.groupTree.setChecked(node.nid, true)
          }
        })
      })
    },
    // 删除按钮
    removeList(list, index) {
      //记录删除的关联关系
      this.delGroupList.push(list[index])
      list.splice(index, 1)
      this.$forceUpdate()
    },
    // 组过滤
    groupFilter(value, data, node) {
      return data.obj.groupType === 'dispatchgroup'
    },
    // 组选择框改变
    groupCheckChange(node, checked) {
      if (checked) {
        if (!this.formData.group.some((g) => g.groupID === node.obj.groupID)) {
          this.formData.group.push({
            groupID: node.obj.groupID,
            groupName: node.obj.groupName,
          })
        }
      } else {
        let index = this.formData.group.findIndex(
          (g) => g.groupID === node.obj.groupID
        )
        if (idnex !== -1) this.formData.group.splice(index, 1)
      }
    },
    // 监听鼠标事件
    clickEvent(e) {
      var box = document.getElementsByClassName(
        `default-select-tree groupTree`
      )[0]
      if (box && !box.contains(e.target)) {
        this.showTree = false
      }
    },
    //组选择确定
    commitGroup() {
      let group = this.$refs.groupTree.getCurrentNode()
      if (group.children.length > 0) {
        this.$message.warning('请选择调度组')
        return
      }
      this.form.group[this.groupIndex].groupID = group.id
      this.form.group[this.groupIndex].groupName = group.label
      this.showTree = false
      this.$forceUpdate()
    },
    handleAddClose() {
      this.acdDialogAdd = false
    },
    //创建ACD
    handleCreate() {
      if (this.form.group.length == 0) {
        this.$message.warning(this.$t('m.tip.ACD_ADD_FAIL_TIP'))
        return
      }
      this.$refs['form'].validate((valid) => {
        if (valid) {
          let form = this.form
          form['@id'] = '100000'
          form['@type'] = 'AcdGroupAdd'
          let obj = {
            request: form,
          }
          dataflow(obj).then((res) => {
            if (res.status != 200) {
              this.$message.warning('新增失败')
            } else {
              this.acdDialogAdd = false
              this.init()
            }
          })
        }
      })
    },
    //修改
    handleUpdate() {
      if (this.form.group.length == 0) {
        this.$message.warning(this.$t('m.tip.ACD_ADD_FAIL_TIP'))
        return
      }
      this.$refs['form'].validate((valid) => {
        if (valid) {
          let form = this.form
          form['@id'] = '100000'
          form['@type'] = 'AcdGroupMod'
          let obj = {
            request: form,
          }
          dataflow(obj).then((res) => {
            if (res.status != 200) {
              this.$message.warning('修改失败')
            } else {
              this.acdDialogAdd = false
              this.init()
            }
          })
        }
      })
    },
    //删除
    handledel() {
      let _this = this
      let delArr = this.$refs.acdTable.store.states.selection
      if (delArr.length == 0) {
        this.$message.warning(this.$t('m.tip.DEL_EMPTY_TIP'))
        return
      }
      this.$confirm(this.$t('m.tip.DELECT_TIP'), this.$t('m.tip.TIPS'), {
        confirmButtonText: this.$t('m.CONFIRM'),
        cancelButtonText: this.$t('m.CANCEL'),
        type: 'warning',
      }).then(() => {
        delArr.forEach((e) => {
          let obj = {
            request: {
              '@id': '100000',
              '@type': 'AcdGroupDel',
              acdGroupID: e.acdGroupID,
            },
          }
          dataflow(obj).then((res) => {
            this.init()
          })
        })
      })
    },
    //查找策略配置
    handleGetAcd(id) {
      let _this = this
      getAcd(id).then((res) => {
        let list = res.data.eventdata
        list.forEach((e) => {
          e.priority = Number(e.priority)
          const g = _this.groupMap.get(e.groupID)
          if (g) e.groupName = g.label
        })
        _this.form.group = res.data.eventdata
        _this.$forceUpdate()
      })
    },
    //添加/修改/删除策略配置
    handleAddACD(id) {
      this.form.group.forEach((e) => {
        if (e.acdID) {
          let obj = {
            request: {
              '@id': '100000',
              '@type': 'AcdMod',
              acdID: e.acdID,
              groupID: e.groupID,
              priority: e.priority,
              acdGroupID: id,
            },
          }
          dataflow(obj).then((res) => {})
        } else {
          let obj = {
            request: {
              '@id': '100000',
              '@type': 'AcdAdd',
              groupID: e.groupID,
              priority: e.priority,
              acdGroupID: id,
            },
          }
          dataflow(obj).then((res) => {})
        }
      })
      //删除
      if (this.delGroupList.length > 0) {
        this.delGroupList.forEach((e, index) => {
          if (e.acdID) {
            let ovj = {
              request: {
                '@id': '100000',
                '@type': 'AcdDel',
                acdID: e.acdID,
              },
            }
            dataflow(obj).then((res) => {})
          }
          this.delGroupList = []
        })
      }
    },
    //关闭新增
    dialogClose() {
      this.acdDialogAdd = false
      this.form = { group: [] }
    },
  },
  mounted() {
    this.init()
    SDK.setEventMore(this.eventMore)
    this.$nextTick(() => {
      document.addEventListener('click', this.clickEvent, true)
    })
  },
  destroyed() {
    document.removeEventListener('click', this.clickEvent, true)
  },
}
</script>

<style lang="scss" scoped>
/deep/.acd-dialog {
  width: 900px;
  height: 500px;
  background-color: #1a4969;
  margin: 0 !important;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  cursor: default;
  background-color: #1a4969;
  .el-dialog__header {
    padding-top: 10px;
    text-align: center;
    .el-dialog__title {
      color: #fff;
    }
    .el-dialog__close {
      color: #fff;
    }
  }
  .el-dialog__body {
    padding: 0 15px;
    .search-input {
      margin-bottom: 10px;
      .el-input__inner {
        background-color: #1a4969;
        color: #fff;
        width: 50%;
      }
    }
  }
  .el-dialog__footer {
    padding-bottom: 10px;
    .el-button {
      background-color: #1a4969;
      color: #fff;
      width: 70px;
    }
    .el-button:hover {
      background-color: #00b2ee;
    }
  }
  .el-table {
    td {
      border-bottom: 1px solid #2e67a8;
    }
    tr:hover > td {
      background-color: #2f6b8d;
    }
    background-color: #1a4969;
    .table-herder-custom {
      background-color: #2e67a8;
      color: #fff;
    }
    .table-cell-custom {
      background-color: #172a47;
      color: #fff;
      .el-link {
        color: #fff;
        margin-left: 20px;
        span {
          font-size: 10px;
        }
        &:hover {
          color: #06f7bb;
        }
      }
    }
    /deep/.el-table__body tr.current-row > td {
      background: #6bb5e6 !important;
    }
  }
  .el-dialog__wrapper {
    position: absolute;
    height: 100%;
    .inner-dialog {
      background-color: #1a4969;
      height: 100%;
      margin-top: 0 !important;
      margin-bottom: 0px;
      opacity: 0.96;
      .el-dialog__footer {
        position: absolute;
        bottom: 0px;
        right: 0px;
      }
      .back-to-list {
        color: #fff;
        height: 22px;
        width: 22px;
        cursor: pointer;
      }
      .el-form {
        .el-form-item__label {
          color: #fff;
        }
        .el-form-item__content {
          width: 40%;
        }
        .el-input__inner,
        .el-textarea__inner {
          background-color: #1a4969;
          color: #fff;
        }
        .group-item {
          display: flex;
          flex-wrap: nowrap;
          align-items: center;
          .svg-icon {
            width: 19px;
            height: 19px;
            margin-right: 5px;
            cursor: pointer;
          }
          .add-label {
            color: #fff;
            cursor: pointer;
          }
          .el-input__inner {
            width: 240px;
          }
          &.add {
            margin-left: -1px;
            font-size: 13px;
            label {
              margin-left: 3px;
            }
            .valid-rule {
              color: #f56c6c;
              margin-left: 20px;
              font-size: 12px;
            }
          }
          .set-defaultNo {
            margin-left: 10px;
            font-style: oblique;
            .el-radio__label {
              font-size: 10px;
            }
          }
          .img-threeDian {
            width: 40px;
            border: 1px solid gray;
            background-color: whitesmoke;
          }
          .img-threeDian:hover {
            border: 1px solid rgb(60, 60, 151);
            background-color: rgb(122, 213, 243);
          }
        }
      }
      .el-upload {
        .el-button {
          color: #fff;
          background-color: #1a4969;
          margin-top: 10px;
          &:hover {
            background-color: #00b2ee;
          }
        }
      }
    }

    .trial-box {
      position: absolute;
      left: calc(50% - 100px);
      top: calc(50% - 50px);
      border: 1px solid rgba(255, 255, 255, 0.6);
      border-radius: 5px;
      width: 200px;
      height: 100px;
      display: flex;
      flex-flow: column;
      align-items: center;
      justify-content: center;
      .el-row {
        color: #fff;
      }
      .trial-loading {
        width: 20px;
        height: 20px;
        border-radius: 50%;
        -webkit-animation: loading 1.1s infinite linear;
        animation: loading 1.2s infinite linear;
        @-webkit-keyframes loading {
          from {
            transform: rotate(0deg);
          }
          to {
            transform: rotate(360deg);
          }
        }
        @keyframes loading {
          from {
            transform: rotate(0deg);
          }
          to {
            transform: rotate(360deg);
          }
        }
      }
      .el-button {
        width: 70px;
        color: #fff;
        background-color: #1a4969;
        margin-top: 10px;
        &:hover {
          background-color: #00b2ee;
        }
      }
      .form-item-group {
        margin: 5px 0;
        .svg-button {
          height: 32px;
          display: flex;
          align-items: center;
          margin-bottom: 18px;
        }
      }
    }
  }
  .default-select-tree {
    right: 30px;
    position: absolute;
    bottom: 15%;
    height: 400px;
    width: 220px;
    background-color: #155175;
    border: 1px solid #fff;
    border-radius: 7px;
    z-index: 999999;
    .tree-scrollbar {
      border-radius: 7px;
      width: 100%;
      height: calc(100% - 40px);
      // background-color: #172a47;
      background-color: #155175;

      .el-tree {
        background-color: #155175 !important;
        color: #fff;
        /deep/.el-tree-node__content {
          height: 34px;
          cursor: default;
          background-color: #155175;
          &:hover {
            background-color: #616d70;
          }
        }
        /deep/.el-tree-node.is-current > .el-tree-node__content {
          background-color: #00b2ee !important;
          color: #ffffff;
        }
        .el-checkbox__input.is-checked {
          .el-checkbox__inner {
            background-color: green;
            border-color: green;
          }
        }
      }
    }
    /deep/.tree-scrollbar__wrap {
      width: auto;
      overflow-x: hidden;
      margin-right: -20px !important;
    }
    text-align: center;
    .el-button {
      width: 70px;
      padding: 9px 0px;
      background-color: #1a4969;
      color: #ffffff;
      &:hover {
        background-color: #409eff;
      }
    }
  }
}
</style>